package com.qdsg.modulesihealsdk.detectStrategy.strategy.Spo2Strategy;

import android.content.Context;

import com.example.moduleutils.LogUtil;
import com.google.gson.Gson;
import com.qdsg.modulesihealsdk.detectStrategy.control.StrategyCallback;
import com.qdsg.modulesihealsdk.entity.Spo2ResultEntity;
import com.qdsg.modulesihealsdk.utils.SihealSdkConstant;
import com.qdsg.modulesihealsdk.detectStrategy.control.DetectBusiness;
import com.siheal.device.reader.measure.BloodOxygenReader;
import com.siheal.device.reader.singlechip.DataChannelReader;
import com.siheal.entitys.device.DeviceOp;
import com.siheal.entitys.measure.BloodOxygenEntity;
import com.siheal.exception.BasicException;

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2022/11/21 11:52
 */
public class Spo2Strategy implements DetectBusiness {
    private DataChannelReader dataChannelReader;
    private BloodOxygenReader bloodOxygenReader;
    private Context context;
    private BloodOxygenEntity bloodOxygenEntity;
    /**
     *
     * haveGetReceive：是否已出值标志，防止出值后还去调用process方法
     */
    private Boolean haveGetReceive = false;
    private int detectType;
    private Spo2Callback spo2Callback;
    @Override
    public void dealDetect(Context context, StrategyCallback strategyCallback) {
        this.context = context;
        haveGetReceive = false;
        if (strategyCallback instanceof Spo2Callback){
            spo2Callback = (Spo2Callback)strategyCallback;
            detectBloodOxygen();
        }
    }

    public Spo2Strategy setDetectType(int detectType){
        this.detectType = detectType;
        return this;
    }

    @Override
    public void stopThread() {
        try {
            if (bloodOxygenReader != null){
                bloodOxygenReader.stopRead();
                bloodOxygenReader = null;
            }


        }catch (Exception e){

        }
        haveGetReceive = false;
        if (spo2Callback != null){
            spo2Callback = null;
        }
    }

    private void detectBloodOxygen(){

        dataChannelReader = (new DataChannelReader(SihealSdkConstant.channelID_SPO2, context){
            // 数据通道切换成功，开始调用血氧读值方法
            @Override
            public void resultReceived(DeviceOp result) {
                bloodOxygenReader = (new BloodOxygenReader("oxygen", context) {
                    //血氧数据获取成功，开始做后续数据处理，当前操作将结果数据回显至H5页面
                    //获取一次结果(最终结果)，在此方法中接收检测结果
                    @Override
                    public void resultReceived(BloodOxygenEntity result) {
                        final String data = new Gson().toJson(result);
                        LogUtil.logAndWrite("__spo2-resultReceived",data);
//                      {"MeasureType":"oxygen","assess":"NORMAL","assessOxygen":"NORMAL","assessPulse":"NORMAL","hasFinger":true,"oxygenValue":99,"pulseValue":78,"c":"f7b416425c674fea944dd1abff82c556","d":0,"e":0,"gen_plan":true,"a":1668750533851,"b":0}
                        //得到数据
                        if (spo2Callback != null && !haveGetReceive){
                            haveGetReceive = true;
                            spo2Callback.resultReceived(new Spo2ResultEntity(result,detectType));
                        }
                    }

                    //检测过程中设备按一定的频率返回检测结果
                    //后续处理可在一定的时间范围内选择最稳定的值作为结果显示在页面上
                    @Override
                    public void process(BloodOxygenEntity middleResult) {
                        //此方法有值返回，语音播报"手指已放入，正在测量中"
//                                    Boolean isHasFinger = middleResult.isHasFinger();

                        final String data = new Gson().toJson(middleResult);
                        LogUtil.logAndWrite("__spo2-process",data);

                        if (!haveGetReceive && spo2Callback != null){
                            if (middleResult.getPulseValue() != 0 || middleResult.getOxygenValue() != 0){
                                spo2Callback.process(new Spo2ResultEntity(middleResult,detectType));
                            }

                            if (middleResult.getOxygenValue() != 0 || middleResult.getPulseValue() != 0 ){
                                bloodOxygenEntity = middleResult;
                            }
                        }

                        //得到数据
//                                    if(isHasFinger){
//                                        // 语音播报"手指已放入，正在测量中"
//                                        // middleResult数据刷新展示
//                                      /*  String data = new Gson().toJson(middleResult);
//                                        //得到数据
//                                        runJavascriptData(measureType, 1, data);*/
//                                    }else{
//                                        //语音播报"等待手指放入测量夹..."
//                                    }
                    }

                    //调用过程中出现的异常
                    @Override
                    public void occurError(BasicException e) {
                                   /*
                                    code = -1 测量值偏低，请将体温仪靠近额头再测量
                                    int MEASURE_OUT_RANGE_EXCEPTION = 1001;//超出范围 temperature <= 32 || temperature >= 42.9
                                    int MEASURE_ASSESS_EXCEPTION = 1002;//结果评估异常
                                    int MEASURE_TIME_OUT = 1005;//测量超时
                                   */
                        String data = new Gson().toJson(e);
                        LogUtil.logAndWrite("__spo2-occurError",data);
                        if (spo2Callback != null){
                            spo2Callback.occurError(e);
                        }

                    }
                });
                if (bloodOxygenReader != null){
                    bloodOxygenReader.start();
                }
            }
            //数据通道切换process方法，实现了父类抽象方法，在此无实义
            @Override
            public void process(DeviceOp middleResult) {}
            //数据通道切换异常处理方法
            @Override
            public void occurError(BasicException exception) {
                if (spo2Callback != null){
                    spo2Callback.occurError(exception);
                }

                          /*  int ERROR_IO = 1;     //打开设备" + device.getDeviceID() + "数据通道异常
                            int ERROR_WRITE_DATA = 2;//设备" + device.getDeviceID() + "写入数据发生异常
                            int ERROR_USB_NOT_FOUND = 2001;//没有找到指定地址下(" + device.getPath() + ")设备
                            int ERROR_USB_NOT_SUPPORT = 2002;//本系统不支持USB模块
                            int ERROR_USB_UNKONW_TYPE = 2003;//未知的USB设备类型
                            int ERROR_USB_REQUEST_PERMISSION = 2004;//请求usb权限失败
                             int MEASURE_PROBE_CONFIG_ERROR = 1008;//配置文件配置错误
                            int ERROR_USB_DEVICE_OPEN = 2005;//打开usb设备错误*/
            }
        });
        if (dataChannelReader != null){
            dataChannelReader.start();
        }
    }

}
